package com.yidu.qianfeng.service.impl;

import com.yidu.qianfeng.common.util.JsonMsgUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: 匡兆杰
 * @Description: 登录失败逻辑
 * @Date Created in 10:23 2021/3/16
 */

@Component
public class QfFailedHandler extends SimpleUrlAuthenticationFailureHandler {

    /**
     * 登录失败处理
     * @param request 请求对象
     * @param response 响应对象
     * @param exception
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //设置响应编码
        response.setCharacterEncoding("UTF-8");
        //设置请求头
        response.setHeader("contentType", "text/json; charset=utf-8");

        //获取writer输出流
        PrintWriter writer = response.getWriter();
        //生成json回应消息
        String msg = JsonMsgUtil.createJsonMessage(0, "登录成功", "登录失败，账号或密码错误!");
        //输出write方法
        writer.write(msg);
        //刷星输出流
        writer.flush();
        //关闭输出流
        writer.close();
    }
}
